<?php
/**
 * TbSyncLogDao.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/11/16- 5:13 下午
 */

namespace common\dao;


use common\exception\ValidatorException;
use common\models\PddSyncLog;
use Yii;
class PddSyncLogDao
{
    /**
     * 写入
     * @param array $data
     * @return PddSyncLog
     * @throws ValidatorException
     */
    public function insertData(array $data)
    {
        $syncLog = new PddSyncLog();

        $syncLog->load($data,'');

        if (!$syncLog->validate()) {
            throw new ValidatorException($syncLog->errorsToString());
        }

        if($syncLog->save())
        {
            return $syncLog;
        }else{
            throw new ValidatorException($syncLog->errorsToOneString());
        }
    }


    /**
     * 通过主键获取信息
     * @param int $id
     * @return PddSyncLog|null
     */
    public function getInfoByPk(int $id)
    {
        return PddSyncLog::findOne(['id'=>$id]);
    }


    /**
     * 获取最新一条同步记录
     * @param int $uid
     * @param int $mall_id
     * @return array|\yii\db\ActiveRecord|null
     */
    public function getLastLogInfo(int $uid,int $mall_id)
    {
        return PddSyncLog::find()
            ->where(['uid'=>$uid,'mall_id'=>$mall_id])
            ->orderBy('id desc')->one();
    }

    /**
     * 获取批次号名称
     * @param int $uid
     * @param int $mall_id
     * @return string
     */
    public function getBatchName(int $uid,int $mall_id,string $type)
    {
        $cacheKey = date('Ymd').':'.$type.':'.$uid.':'.$mall_id;


        $cacheNum = Yii::$app->redis->get($cacheKey);

        if(!$cacheNum)
        {
            Yii::$app->redis->setex($cacheKey,86400,1);

            return date('Ymd').'-'.$type.'-'.sprintf("%04d", 1);
        }else{
            Yii::$app->redis->incr($cacheKey);
            return date('Ymd').'-'.$type.'-'.sprintf("%04d", $cacheNum+1);
        }

    }
}
